package com.yamaha.bikemarket;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.RequestParams;
import com.yamaha.bikemarket.api.API;
import com.yamaha.bikemarket.util.LogUtil;
import com.yamaha.bikemarket.util.SCStaticFunc;
import com.yamaha.bikemarket.util.Utils;

public class WantToBuyEditFragment extends AMyActivity implements
		OnEditorActionListener {

	private String temp;
	private JSONObject item;
	private boolean isCreated;

	public WantToBuyEditFragment() {
		super(MenuType.NONE);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.wb_edit_layout);

		temp = getIntent().getStringExtra("temp");

		final Button brandButton = (Button) findViewById(R.id.wb_brand);
		final Button modelButton = (Button) findViewById(R.id.wb_model);
		final Button colorButton = (Button) findViewById(R.id.wb_color);
		final Button regYearButton = (Button) findViewById(R.id.wb_regyear);
		final Button saveButton = (Button) findViewById(R.id.wb_save);

		brandButton.setOnClickListener(this);
		modelButton.setOnClickListener(this);
		colorButton.setOnClickListener(this);
		regYearButton.setOnClickListener(this);
		saveButton.setOnClickListener(this);

		final EditText regNo = (EditText) findViewById(R.id.wb_regno);
		final EditText machineNo = (EditText) findViewById(R.id.wb_machine_no);
		final EditText priceMin = (EditText) findViewById(R.id.wb_price_min);
		final EditText priceMax = (EditText) findViewById(R.id.wb_price_max);

		final CheckBox isDealerOnly = (CheckBox) findViewById(R.id.wb_dealer_only);

		regNo.setOnEditorActionListener(this);
		machineNo.setOnEditorActionListener(this);
		priceMin.setOnEditorActionListener(this);
		priceMax.setOnEditorActionListener(this);

		setListenerForMenu();

		// Edit Mode
		final String detail = getIntent().getStringExtra("detail");
		if (null != detail && temp != null) {
			try {
				item = new JSONObject(detail);

				priceMax.setText(item.getString("price_max"));
				priceMin.setText(item.getString("price"));
				regNo.setText(item.getString("reg_no"));
				machineNo.setText(item.getString("machine_no"));

				final String isD = item.getString("is_dealer_only");
				if ("0".equals(isD)) {
					isDealerOnly.setChecked(false);
				} else {
					isDealerOnly.setChecked(true);
				}

				// Brand
				brandButton.setText(item.getString("brand_name"));
				JSONArray array = (JSONArray) SCStaticFunc.getData(this,
						SCStaticFunc.BAND);
				for (int i = 0; i < array.length(); i++) {
					final JSONObject a = array.getJSONObject(i);
					if (a.getInt("brand_id") == item.getInt("brand_id")) {
						brandButton.setTag(a);
						break;
					}
				}

				// Model
				modelButton.setText(item.getString("model_name"));
				for (int i = 0; i < array.length(); i++) {
					final JSONObject a = array.getJSONObject(i);
					final JSONArray mm = a.getJSONArray("model");

					for (int j = 0; j < mm.length(); j++) {
						final JSONObject m = mm.getJSONObject(j);

						if (m.getInt("model_id") == item.getInt("model_id")) {
							modelButton.setTag(m);
						}
					}
				}

				// Color
				array = (JSONArray) SCStaticFunc.getData(this,
						SCStaticFunc.COLOR);
				colorButton.setText(item.getString("color_name"));
				for (int i = 0; i < array.length(); i++) {
					final JSONObject a = array.getJSONObject(i);
					if (a.getInt("color_id") == item.getInt("color_id")) {
						colorButton.setTag(a);
						break;
					}
				}

				regYearButton.setText(item.getString("reg_year"));
				regYearButton.setTag(item.getString("reg_year"));

			} catch (JSONException e) {
				LogUtil.e("WantToBuyEditFragment", e.getMessage(), e);

				if (null != temp && temp.length() > 0) {
					Toast.makeText(this, "Something Error", Toast.LENGTH_SHORT)
							.show();
					finish();
				}
			}
		}

		isCreated = true;
	}

	@Override
	protected List<EditText> getEditTexts() {

		final ArrayList<EditText> list = new ArrayList<EditText>();

		if (isCreated) {

			final EditText regNo = (EditText) findViewById(R.id.wb_regno);
			final EditText machineNo = (EditText) findViewById(R.id.wb_machine_no);
			final EditText priceMin = (EditText) findViewById(R.id.wb_price_min);
			final EditText priceMax = (EditText) findViewById(R.id.wb_price_max);

			list.add(regNo);
			list.add(machineNo);
			list.add(priceMin);
			list.add(priceMax);

		}

		return list;
	}

	@Override
	public void onClick(View v) {
		if (onMenuClick(v)) {
			return;
		}

		switch (v.getId()) {
		case R.id.wb_brand: {
			handleBand();
		}
			break;
		case R.id.wb_color: {
			handleColor();
		}
			break;
		case R.id.wb_model: {
			handleModel();
		}
			break;

		case R.id.wb_regyear: {
			handleRegYear();
		}
			break;
		case R.id.wb_save: {
			handleSave();
		}
			break;
		case R.id.wb_delete_button: {
			handleDelete();
		}
			break;
		}
	}

	private void handleDelete() {

		final RequestParams params = new RequestParams();
		params.put("temp", temp);

		final AsyncHttpClient client = new AsyncHttpClient();

		client.post(API.DELETE_WANT_TO_BUY, params,
				new MyAsyncHttpResponseHandler(API.DELETE_WANT_TO_BUY, this) {

					@Override
					public void onStart() {
						super.onStart();
						Utils.showProgressDialog(WantToBuyEditFragment.this,
								"", "Deleting...");
					}

					@Override
					public void onSuccess(String r) {
						super.onSuccess(r);

						try {
							final JSONObject obj = new JSONObject(r);

							Toast.makeText(WantToBuyEditFragment.this,
									"Deleted...", Toast.LENGTH_SHORT).show();

							LogUtil.i("WantToBuyEditFragment", "Deleted... "
									+ temp);

							Utils.closeAllDialog();

							finish();

						} catch (JSONException e) {
							LogUtil.e("WantToBuyEditFragment", e.getMessage(),
									e);
						}
					}
				});
	}

	//
	private void handleBand() {

		final Button brandButton = (Button) findViewById(R.id.wb_brand);

		try {

			final List<String> data = new ArrayList<String>();

			final JSONArray array = (JSONArray) SCStaticFunc.getData(this,
					SCStaticFunc.BAND);

			for (int i = 0; i < array.length(); i++) {
				final JSONObject obj = array.getJSONObject(i);

				final String name = obj.getString("name");
				data.add(name);
			}

			showDialog(data, new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();

					try {
						final JSONObject obj = (JSONObject) array.get(which);
						brandButton.setText(obj.getString("name"));
						brandButton.setTag(obj);
					} catch (JSONException e) {
						LogUtil.e("WantToBuyEditFragment",
								"handleBrand: " + e.getMessage(), e);
					}
				}

			});

		} catch (JSONException e) {
			LogUtil.e("WantToBuyEditFragment",
					"handleBrand: " + e.getMessage(), e);
		}
	}

	//
	private void handleRegYear() {

		final Button btn = (Button) findViewById(R.id.wb_regyear);

		final List<String> data = new ArrayList<String>();
		try {
			final JSONArray array = (JSONArray) SCStaticFunc.getData(this,
					SCStaticFunc.YEAR);
			for (int i = 0; i < array.length(); i++) {
				data.add(array.getString(i));
			}
		} catch (JSONException e) {
			LogUtil.e("WantToBuyEditFragment",
					"handleRegYear : " + e.getMessage(), e);
		}

		showDialog(data, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();

				final String val = (2000 + which) + "";
				LogUtil.v("Reg Year", val);
				btn.setText(val);
				btn.setTag(val);
			}

		});

	}

	//
	private void handleModel() {

		final Button btn = (Button) findViewById(R.id.wb_model);

		try {

			final List<String> data = new ArrayList<String>();

			final JSONArray array = (JSONArray) SCStaticFunc.getData(this,
					SCStaticFunc.BAND);

			final List<JSONObject> mList = new ArrayList<JSONObject>();

			for (int i = 0; i < array.length(); i++) {
				final JSONObject obj = array.getJSONObject(i);

				final JSONArray model = obj.getJSONArray("model");
				for (int j = 0; j < model.length(); j++) {
					final JSONObject mObj = model.getJSONObject(j);

					mList.add(mObj);

					final String name = mObj.getString("name");
					data.add(name);
				}
			}

			showDialog(data, new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();

					try {
						final JSONObject obj = mList.get(which);
						btn.setText(obj.getString("name"));
						btn.setTag(obj);
					} catch (JSONException e) {
						LogUtil.e("WantToBuyEditFragment",
								"handleModel : " + e.getMessage(), e);
					}

				}

			});

		} catch (JSONException e) {
			LogUtil.e("WantToBuyEditFragment",
					"handleModel : " + e.getMessage(), e);
		}
	}

	//
	private void handleColor() {

		final Button btn = (Button) findViewById(R.id.wb_color);

		try {

			final List<String> data = new ArrayList<String>();

			final JSONArray array = (JSONArray) SCStaticFunc.getData(this,
					SCStaticFunc.COLOR);

			for (int i = 0; i < array.length(); i++) {
				final JSONObject obj = array.getJSONObject(i);

				final String name = obj.getString("name");
				data.add(name);
			}

			showDialog(data, new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();

					try {
						final JSONObject obj = (JSONObject) array.get(which);
						btn.setText(obj.getString("name"));
						btn.setTag(obj);
					} catch (JSONException e) {
						LogUtil.e("WantToBuyEditFragment",
								"handleColor : " + e.getMessage(), e);
					}

				}

			});

		} catch (JSONException e) {
			LogUtil.e("WantToBuyEditFragment",
					"handleColor : " + e.getMessage(), e);
		}
	}

	private void showDialog(final List<String> data,
			final DialogInterface.OnClickListener listener) {

		final AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Choose item...");
		builder.setItems(data.toArray(new String[data.size()]), listener);
		builder.create().show();
	}

	//
	@Override
	public boolean onEditorAction(final TextView edittext, final int keyCode,
			final KeyEvent event) {
		if ((keyCode == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_DOWN)
				|| (keyCode == EditorInfo.IME_ACTION_DONE)) {
			hideInputText();
			return true;
		}
		return false;
	}

	//
	private void handleSave() {
		final Button brandButton = (Button) findViewById(R.id.wb_brand);
		final Button modelButton = (Button) findViewById(R.id.wb_model);
		final Button colorButton = (Button) findViewById(R.id.wb_color);
		final Button regYearButton = (Button) findViewById(R.id.wb_regyear);
		final EditText regNo = (EditText) findViewById(R.id.wb_regno);
		final EditText machineNo = (EditText) findViewById(R.id.wb_machine_no);
		final EditText priceMin = (EditText) findViewById(R.id.wb_price_min);
		final EditText priceMax = (EditText) findViewById(R.id.wb_price_max);
		final CheckBox dealerOnly = (CheckBox) findViewById(R.id.wb_dealer_only);

		final String msg;
		if (brandButton.getTag() == null) {
			msg = "Brand requires a value.";
		} else if (modelButton.getTag() == null) {
			msg = "Model requires a value.";
		} else if (colorButton.getTag() == null) {
			msg = "Color requires a value.";
		} else if (priceMin.getText().toString().trim().length() == 0) {
			msg = "Price (min) requires a value.";
		} else if (priceMax.getText().toString().trim().length() == 0) {
			msg = "Price (max) requires a value.";
		} else {
			msg = "";
		}

		if (msg.length() > 0) {
			Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
			LogUtil.w("WantToBuyEditFragment", "Save Validation Error : " + msg);
		} else {

			final Button saveButton = (Button) findViewById(R.id.wb_save);
			saveButton.setEnabled(false);

			try {
				final JSONObject brandObj = (JSONObject) brandButton.getTag();
				final JSONObject modelObj = (JSONObject) modelButton.getTag();
				final JSONObject colorObj = (JSONObject) colorButton.getTag();
				final String regYearObj = (String) regYearButton.getTag();
				final String pmin = priceMin.getText().toString();
				final String pmax = priceMax.getText().toString();
				final String rn = regNo.getText().toString();
				final String mn = machineNo.getText().toString();
				final String donly = dealerOnly.isChecked() ? "1" : "0";

				final RequestParams params = new RequestParams();
				params.put("user_id", SCStaticFunc.getUserId(this));

				// For Edit
				if (temp != null && temp.length() > 0) {
					params.put("temp", temp);
				}

				if (brandObj != null) {
					params.put("brand_id", brandObj.getString("brand_id"));
				} else {
					params.put("brand_id", "");
				}
				if (modelObj != null) {
					params.put("model_id", modelObj.getString("model_id"));
				} else {
					params.put("model_id", "");
				}
				if (colorObj != null) {
					params.put("color_id", colorObj.getString("color_id"));
				} else {
					params.put("color_id", "");
				}
				if (pmin != null) {
					params.put("price_min", pmin);
				} else {
					params.put("price_min", "");
				}
				if (pmax != null) {
					params.put("price_max", pmax);
				} else {
					params.put("price_max", "");
				}
				if (rn != null) {
					params.put("reg_no", rn);
				} else {
					params.put("reg_no", "");
				}
				if (regYearObj != null) {
					params.put("reg_year", regYearObj);
				} else {
					params.put("reg_year", "");
				}
				if (mn != null) {
					params.put("machine_no", mn);
				} else {
					params.put("machine_no", "");
				}
				params.put("dealer_only", donly);

				LogUtil.i("WantToBuyEditFragment",
						"Save Param : " + params.toString());

				final AsyncHttpClient client = new AsyncHttpClient();
				client.post(API.SAVE_WANT_TO_BUY, params,
						new MyAsyncHttpResponseHandler(API.SAVE_WANT_TO_BUY,
								this) {

							@Override
							public void onStart() {
								super.onStart();

								Utils.showProgressDialog(
										WantToBuyEditFragment.this, "",
										"Saving...");
							}

							@Override
							public void onSuccess(final String r) {
								super.onSuccess(r);

								try {
									final JSONObject obj = new JSONObject(r);

									if (obj.getBoolean("success")) {

										LogUtil.i("WantToBuyEditFragment",
												"Saved Success");

										Toast.makeText(
												WantToBuyEditFragment.this,
												"Saved...", Toast.LENGTH_SHORT)
												.show();

										Utils.closeAllDialog();
										finish();

									} else {

										LogUtil.w(
												"WantToBuyEditFragment",
												"Saved Failed : "
														+ obj.getString("message"));

										Utils.closeAllDialog();

										Toast.makeText(
												WantToBuyEditFragment.this,
												obj.getString("message"),
												Toast.LENGTH_SHORT).show();
									}
								} catch (JSONException e) {
									LogUtil.e("WantToBuyEditFragment",
											"Error : " + e.getMessage(), e);
								}
							}

							@Override
							public void onFinish() {
								super.onFinish();

								saveButton.setEnabled(true);
							}

						});
			} catch (JSONException e) {
				LogUtil.e("WantToBuyEditFragment", e.getMessage(), e);
				saveButton.setEnabled(true);
			}

		}
	}
}
